/*
 * @Author: yangshangchao
 * @Date: 2025-01-13 09:18:39
 * @LastEditors: yangshangchao
 * @Description: 头部注释
 */
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react-swc';
import type { Plugin } from 'vite';
import mockjs from 'mockjs';
// 根据路由传进的url 改变mockjs数据的key为 name的值 eg: http://localhost:3000/api/list?keyWord=james
import url from 'node:url';

// 1.vite插件
const viteMockServer = (): Plugin => {
  return {
    name: 'vite-mock-server',
    // 通过 钩子configureServer 返回当前服务
    configureServer(server) {
      server.middlewares.use('/api/list', (req, res) => {
        res.setHeader('content-type', 'application/json');
        // 获取原始url的参数
        const parseUrl = url.parse(req.originalUrl, true).query;
        // true的作用 解析url的参数变成对象  http://localhost:3000/api/list?keyWord=james&page=1&pageSize=10  => {keyWord: 'james', page: '1', pageSize: '10'}
        const data = mockjs.mock({
          'list|1000': [
            {
              'id|+1': 1,
              name: parseUrl.keyWord,
              address: '@county(true)',
            },
          ],
        });
        res.end(JSON.stringify(data));
      });
    },
  };
};
// https://vite.dev/config/
export default defineConfig({
  plugins: [react(), viteMockServer()],
});
